package microarray;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.StringTokenizer;

import javax.jdo.PersistenceManager;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import org.apache.tools.tar.TarInputStream;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.urlfetch.FetchOptions;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
import com.google.appengine.api.urlfetch.FetchOptions.Builder;

@PersistenceCapable
public class Platform {
	@PrimaryKey
    @Persistent
	private Key key;
	
	@Persistent
	HashMap<String, String> geneMap;
	
	public static Platform getPlatform(String gpl) throws IOException
	{
		if (gpl == null)
			return null;
		Platform p = null;
	
		try{
			p = retrievePlatform(gpl);
		} finally {
		if (p == null)
			p = new Platform(gpl);
		}
		return p;
	}
	
	private Platform(String gpl) throws IOException
	{
		key = KeyFactory.createKey(Platform.class.getSimpleName() , gpl);
		
		String urlString = "http://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GPL_HERE&targ=self&view=data&form=text";
		
		urlString = urlString.replace("GPL_HERE", gpl);
		URL url = new URL(urlString);
		
		FetchOptions fetch = Builder.allowTruncate();
		URLFetchService fs = URLFetchServiceFactory.getURLFetchService(); 
		
    	HTTPResponse resp = fs.fetch(new HTTPRequest( url, HTTPMethod.GET, fetch.allowTruncate().setDeadline(15.0)));
    	ByteArrayInputStream in = new ByteArrayInputStream(resp.getContent());
    	
		BufferedReader r = new BufferedReader(new InputStreamReader(in));
		String line = r.readLine();
		while(line != "!platform_table_begin")
			line = r.readLine();
		
		geneMap = new HashMap<String, String>();
		
		while(line != null)
		{
			StringTokenizer tok = new StringTokenizer(line);
			String id = tok.nextToken();
			String gene = tok.nextToken();
			
			geneMap.put(id, gene);
		}
		
        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            pm.makePersistent(this);
        } finally {
            pm.close();
        }
	}
	
	private static Platform retrievePlatform(String gpl) {
	    PersistenceManager pm = PMF.get().getPersistenceManager();
	    Platform detached = null;
	    try {
	        Platform p = pm.getObjectById(Platform.class, KeyFactory.createKey(Platform.class.getSimpleName(),gpl));
	        detached = pm.detachCopy(p);
	    } finally {
	        pm.close();
	    }
	    
	    return detached;
	}
	
	public String getGene(String key)
	{
		return geneMap.get(key);
	}
	
}
//GPL341
//http://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GPL341&targ=self&view=brief&form=text 